package cn.bd13.xinapp.controller.web;

import cn.bd13.xinapp.model.dto.*;
import cn.bd13.xinapp.model.entity.Admin;
import cn.bd13.xinapp.service.web.AdminService;
import cn.bd13.xinapp.utils.RedisUtil;
import cn.bd13.xinapp.utils.ReturnUtils;
import cn.bd13.xinapp.utils.TokenUtils;
import com.alibaba.fastjson.JSON;

import cz.mallat.uasparser.UserAgentInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api("管理员方面的")
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AdminService adminService;


    @ApiOperation(value = "最新的登录",notes = "。。。")
    @ApiResponses({
            @ApiResponse(code = 403,message = "密码错误"),
            @ApiResponse(code = 406,message = "手机号错误"),
            @ApiResponse(code = 502,message = "数据库操作错误")
    })
    @PostMapping(value = "/loginByPwd")
    public ReturnResult loginByPwd(@RequestBody LoginForm loginForm, HttpServletRequest request){

        //检查登录信息是否正确
        try {
            Admin admin = adminService.getAdminByPhone(loginForm.getAphone());

            if (admin!=null){
                if (loginForm.getPassword().equals(admin.getPassword())){
                    //检查正确
                    //解析这个请求的设备信息
                    String userAgent=request.getHeader("User-Agent");
                    UserAgentInfo userAgentInfo= TokenUtils.uaSparser.parse(userAgent);
                    String dType=userAgentInfo.getDeviceType();

                    //生成token
                    String token=TokenUtils.createToken(admin.getAid().toString(),dType);
                    //将token存入redis（先判断redis中有没有）
                    saveToken(token,admin);
                    //这是将用户信息放在data中，token信息放在msg中
                    return ReturnUtils.returnSuccessWithData(admin,token);
//                    Map<String,Object> dataMap=new HashMap<>();
//                    dataMap.put("user",user);
//                    dataMap.put("token",token);
//                    return ReturnUtils.returnSuccessWithData(dataMap);
                }else{
                    //密码错误
                    return ReturnUtils.returnFailed("403");
                }
            }else{
                //手机号错误
                return ReturnUtils.returnFailed("406");
            }
        } catch (Exception e) {
            //查询中出现异常
            e.printStackTrace();
            return ReturnUtils.returnFailed("502");
        }

    }

    @ApiOperation(value = "获取菜单列表",notes = "。。。")
    @ApiResponses({
            @ApiResponse(code = 502,message = "缓存操作错误"),
            @ApiResponse(code = 504,message = "数据库操作错误")
    })
    @GetMapping("/getMenus")
    public ReturnResult getMenus(HttpServletRequest request){
        //通过token，获取这个管理员的信息
        String token = request.getHeader("token");
        String adminJson="";
        try {
            adminJson=redisUtil.get(token);
        }catch (Exception e){
            return ReturnUtils.returnFailed("502","reids error");
        }
        Admin admin;
        //转换为Admin对象
        if (adminJson!=""){
             admin= JSON.parseObject(adminJson,Admin.class);
        }else{
            return ReturnUtils.returnFailed("502","reids error");
        }

        //获取管理员类型
        int adminType=admin.getAdminType();
        //通过类型获取菜单数据
        try {
            List<MenuVo> menus=adminService.getMenusByAtype(adminType);
            return ReturnUtils.returnSuccessWithData(menus);
        }catch (Exception e){
            e.printStackTrace();
            return ReturnUtils.returnFailed("504","mysql error");
        }
    }


//    初始化需要查询
//    关键字可以查询，按照页码，每页多少条
    @ApiOperation(value = "获取菜单列表",notes = "。。。")
    @ApiResponses({
            @ApiResponse(code = 504,message = "数据库操作错误")
    })
    @PostMapping("/getAdminList")
    public ReturnResult getAdminList(@RequestBody QueryAdminInfo queryAdminInfo){
        try {
            System.out.println(queryAdminInfo);
            //查出当前需要的指定页码和关键字的结果
            List<AdminVo> adminList=adminService.queryAdminCtds(queryAdminInfo.getQuery(),queryAdminInfo.getPagenum(),queryAdminInfo.getPagesize());
            //查出总共多少条
            int size=adminService.queryAdminCtdsCount(queryAdminInfo.getQuery());
            //总共两个数据需要返回，可以把size这个简单数据放到msg中，做法比较偷懒
            //正规的做法是通过map对象携带多个数据
            Map<String,Object> data=new HashMap<>();
            data.put("adminList",adminList);
            data.put("total",size);
            return ReturnUtils.returnSuccessWithData(data);
        }catch (Exception e){
            e.printStackTrace();
            return ReturnUtils.returnFailed("504");
        }
    }

    @ApiOperation(value = "修改管理员状态",notes = "。。。")
    @ApiResponses({
            @ApiResponse(code = 504,message = "数据库操作错误")
    })
    @PutMapping("/updAdminStatus/{aid}")
    public ReturnResult updAdminStatus(@PathVariable int aid){
//        System.out.println("shoudao:"+aid);
        try {
            adminService.updAdminStatus(aid);
            return ReturnUtils.returnSuccess();
        }catch (Exception e){
            return ReturnUtils.returnFailed("504");
        }
    }

    @ApiOperation(value = "新增管理员",notes = "。。。")
    @ApiResponses({
            @ApiResponse(code = 504,message = "数据库操作错误")
    })
    @PostMapping("/addAdmin")
    public ReturnResult addAdmin(@RequestBody AddForm addForm){
        System.out.println("收到，新增："+addForm);
        try {
            adminService.addAdmin(addForm);
            return ReturnUtils.returnSuccess();
        }catch (Exception e){
            e.printStackTrace();
            return ReturnUtils.returnFailed("504");
        }

    }



    private void saveToken(String token,Admin admin)throws Exception{

        String tokenKey="user-"+admin.getAid();
        String tokenValue=null;
        if ((tokenValue=redisUtil.get(tokenKey))!=null){
            //用户已经登录过，而且没有过期
            redisUtil.delete(tokenKey);
        }
        //缓存用户(用户id作为key，token作为value)
        redisUtil.set(tokenKey,token,1800);
        //缓存用户信息（token作为key，用户信息的json字符串作为value）
        redisUtil.set(token,JSON.toJSONString(admin),1800);
    }

}

